import { ref } from "vue"
import store from "@/store"
import { defineStore } from "pinia"
import { usePermissionStore } from "./permission"
import { useTagsViewStore } from "./tags-view"
import { useSettingsStore } from "./settings"
import { getToken, removeToken, setToken, getUserName, setUserName, removeUserName } from "@/utils/cache/cookies"
import router, { resetRouter } from "@/router"
import { loginApi, getUserInfoApi, MyloginApi, MygetUserAuthApi } from "@/api/login"
import { type LoginRequestData, type MyLoginRequestData, type RoleRequestData } from "@/api/login/types/login"
import { type RouteRecordRaw } from "vue-router"
import routeSettings from "@/config/route"

export const useUserStore = defineStore("user", () => {
  const token = ref<string>(getToken() || "")
  const roles = ref<string[]>([])
  // const username = ref<string>("")
  const username = ref<string>("")

  // let myusername = ""

  const permissionStore = usePermissionStore()
  const tagsViewStore = useTagsViewStore()
  const settingsStore = useSettingsStore()

  /** 设置角色数组 */
  const setRoles = (value: string[]) => {
    roles.value = value
    console.log(roles)
  }
  /** 登录 */
  const login = async ({ username, password, code }: LoginRequestData) => {
    const { data } = await loginApi({ username, password, code })
    setToken(data.token)
    token.value = data.token
  }

  const mylogin = async ({ username, password, code, userKey, role }: MyLoginRequestData) => {
    const { data } = await MyloginApi({ username, password, code, userKey, role })
    setToken(data)
    //接收到的data就是string 类型
    token.value = data
    console.log(token.value)
  }

  /** 获取用户详情 */
  const getInfo = async () => {
    const { data } = await getUserInfoApi()
    // const { data } = await MygetUserInfoApi()
    console.log(data)
    username.value = data.username
    // 验证返回的 roles 是否为一个非空数组，否则塞入一个没有任何作用的默认角色，防止路由守卫逻辑进入无限循环
    roles.value = data.roles?.length > 0 ? data.roles : routeSettings.defaultRoles
  }

  const mygetInfo = async (myusername: RoleRequestData) => {
    // const { data } = await getUserInfoApi()
    // console.log(myusername)
    const { data } = await MygetUserAuthApi(myusername)
    console.log(data)
    username.value = data[0].username
    console.log(data[0].roles)
    // 验证返回的 roles 是否为一个非空数组，否则塞入一个没有任何作用的默认角色，防止路由守卫逻辑进入无限循环
    roles.value = data[0].roles?.length > 0 ? data[0].roles : routeSettings.defaultRoles
    console.log(roles.value)
  }

  /** 切换角色 */
  const changeRoles = async (role: string) => {
    //用作数据传输
    const userName = { username: "" }
    const newToken = "token-" + role
    token.value = newToken
    setToken(newToken)
    // await getInfo()
    userName.username = getUsername().value
    await mygetInfo(userName)
    permissionStore.setRoutes(roles.value)
    resetRouter()
    permissionStore.dynamicRoutes.forEach((item: RouteRecordRaw) => {
      router.addRoute(item)
    })
    _resetTagsView()
  }
  /** 登出 */
  const logout = () => {
    removeToken()
    removeUserName()
    token.value = ""
    roles.value = []
    resetRouter()
    _resetTagsView()
  }
  /** 重置 Token */
  const resetToken = () => {
    removeToken()
    token.value = ""
    roles.value = []
  }
  /** 重置 Visited Views 和 Cached Views */
  const _resetTagsView = () => {
    if (!settingsStore.cacheTagsView) {
      tagsViewStore.delAllVisitedViews()
      tagsViewStore.delAllCachedViews()
    }
  }

  const getUsername = () => {
    username.value = getUserName() === undefined ? ref<string>("") : getUserName()
    return username
  }

  const setUsername = (myusername: string) => {
    username.value = myusername
    setUserName(myusername)
  }

  return {
    token,
    roles,
    username,
    setRoles,
    login,
    getInfo,
    changeRoles,
    logout,
    resetToken,
    mylogin,
    mygetInfo,
    getUsername,
    setUsername
  }
})

/** 在 setup 外使用 */
export function useUserStoreHook() {
  return useUserStore(store)
}
